package com.cold.manage.task;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


/**
 * 模拟硬件消息
 */
public class MessageTask {

    private Logger logger = LoggerFactory.getLogger(MessageTask.class);
    private Random random = new Random();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void sendMessage(String deviceCode){
        NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new StringEncoder())
                                    .addLast(new StringDecoder());
                        }
                    });
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 11111).sync();
            //随机数据报文
            String msg = random(deviceCode);
            sync.channel().writeAndFlush(msg);
            sync.channel().closeFuture();
        }catch (Exception ex){
            logger.error("发送消息异常",ex);
        }finally {
            workGroup.shutdownGracefully();
        }
    }

    public String random(String deviceCode){
        //随机产生温度 -30 ~ 50
        int tem = random.nextInt(80) - 30;
        //随机湿度 0 ~ 90
        int hum = random.nextInt(90);
        //随机状态 0 停用 1 正常 -1 异常
        int[] states = {0,1,-1};
        //随机经度
        double lon = 90 + random.nextInt(30) + random.nextDouble();
        //随机纬度
        double lat = 30 + random.nextInt(10) + random.nextDouble();
        int state = states[random.nextInt(states.length)];
        String message = String.format("MSG|%s|%d|%d|%d|%f|%f|%s|V1.0",
                deviceCode,tem,hum,state,lon,lat,dateFormat.format(new Date()));
        System.out.println(message);
        return message;
    }
}
